import { defineStore } from "pinia";
import { userInfoDefault } from "@/types/user"
import type { UserInfo, LoginResponse } from "@/types/user"

export const useUserStore = defineStore("user", {
  state: () => ({
    x_login: false,
    x_userInfo: userInfoDefault(),
    // x_user_id: '',
    // x_username: '',
    // x_email: '',
    // x_level: 0,
    x_token: '',
  }),
  getters: {
    // Getters 用于计算派生状态或对现有状态进行转换
    // userInfo(state) { return state.userInfo }, // 返回一个浅拷贝
    // 特别注意，下面名字不能与上面变量名相同
    isLogin(state) { return state.x_login },
    userId(state) { return state.x_userInfo.user_id },
    token(state) { return state.x_token },
    username(state) { return state.x_userInfo.username },
    email(state) { return state.x_userInfo.email },
    level(state) { return state.x_userInfo.level },
  },
  actions: {
    // Actions 用于封装异步操作或复杂的业务逻辑
    setUserInfo(userInfo: UserInfo) {
      this.$patch((state) => {
        state.x_userInfo = userInfo;
      });
    },
    setLoginInfo(loginRsp: LoginResponse) {
      this.$patch((state) => {
        state.x_login = true;
        state.x_userInfo.username = loginRsp.username;
        state.x_userInfo.user_id = loginRsp.user_id;
        state.x_userInfo.level = loginRsp.level;
        state.x_token = loginRsp.new_token;
      });
    },
    reset() {
      this.$patch((state) => {
        state.x_login = false;
        state.x_token = '';
        // state.x_user_id = '';
        // state.x_username = '';
        // state.x_email = '';
        // state.x_level = 0;
        state.x_userInfo = userInfoDefault();
      });
    },
  },
  persist: [
    {
      pick: ['x_login', 'x_userInfo', 'x_token'],
      storage: sessionStorage,
    },
    // {
    //   pick: ['user_id'],
    //   storage: localStorage,
    // },
  ],
});
